using UnityEditor;
using Newtonsoft.Json;
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using UnityEditor.SceneManagement;
using cframework;

public class BuildVersionInfo
{
  public string version;
  public int build_version;
  public int res_version;
  public int pre_res_version;
  public int min_app_version;
  public int max_app_version;
}

public static class EditorCommonTool
{

#if UNITY_5
	public static BuildTarget build_target_ios = BuildTarget.iOS;
#else
	public static BuildTarget build_target_ios = BuildTarget.iOS;
#endif
	public const string versionInfoName = "version_info.json";
	public static string allBundleVersionName = "all_bundle_version.json";
	public static string interfaceFile = "Assets/TempData/raw_interface.json";
	public static string need_rebuild_spritesheet_filepath = "Assets/TempData/raw_sheet.json";

	public static string getProjectPath()
	{
		return Path.GetDirectoryName(Application.dataPath);
	}

	// public static string getBundleConfigPath(Platform platform)
	// {
	// 	string bundleConfigPath = ConfigTool.bundleDir[0] + "/" + platform.ToString() + "/" + BundleManager.configName + ".bytes";
	// 	return bundleConfigPath;
	// }

	public static string getBuildVersionInfoDir()
	{
        return "Assets/TempData/" + EditorCommonTool.getPlatform().ToString() + "/" + AppManager.GetAppInfo().publish_type;
	}

	public static string getVersionInfoPath()
	{
		string configPath = getBuildVersionInfoDir() + "/" + versionInfoName;
		return configPath;
	}

	public static BuildVersionInfo getBuildVersionInfo()
	{
		string configPath = getVersionInfoPath();
		string asset = CommonUtil.fileToString(configPath);
		BuildVersionInfo config = null;
		if(asset != null)
		{
			config = JsonConvert.DeserializeObject<BuildVersionInfo>(asset);
		}
		
		if(config == null)
		{
			config = new BuildVersionInfo();
			config.build_version = 1;
			config.min_app_version = 0;
			config.res_version = 1;
			config.max_app_version = 0;
		}
		
		return config;
	}

	public static void setBuildVersionInfo(string str)
	{
		string configPath = getVersionInfoPath();
		CommonUtil.stringToFile(configPath, str);
	}



	// public static HashSet<string> getBuildAnimConfig()
	// {
	// 	string buildAnimConfig = ConfigTool.bundleDir[0] + "/" + BuildAnimation.buildAnimName;
		
	// 	TextAsset asset = AssetDatabase.LoadAssetAtPath(buildAnimConfig, typeof(TextAsset)) as TextAsset;
	// 	if(asset == null)
	// 	{
	// 		return null;
	// 	}
	// 	HashSet<string> animPaths = JsonConvert.DeserializeObject<HashSet<string>>(asset.text);
	// 	return animPaths;
	// }

	// public static HashSet<string> getBuildCopyConfig(string resPath)
	// {
	// 	string buildAnimConfig = resPath + "/" + BuildAnimation.buildCopyName;
		
	// 	TextAsset asset = AssetDatabase.LoadAssetAtPath(buildAnimConfig, typeof(TextAsset)) as TextAsset;
	// 	if(asset == null)
	// 	{
	// 		return null;
	// 	}
	// 	HashSet<string> animPaths = JsonConvert.DeserializeObject<HashSet<string>>(asset.text);
	// 	return animPaths;
	// }

	public static Platform getPlatform()
	{
		return getPlatform(EditorUserBuildSettings.activeBuildTarget);
	}

	public static Platform getPlatform(this BuildTarget target)
	{
		if(target == BuildTarget.StandaloneOSX)
		{
			return RuntimePlatform.OSXPlayer.getPlatform();
		}
		else if(target == BuildTarget.WebGL)
		{
			return RuntimePlatform.WebGLPlayer.getPlatform();
		}
		else if(target == BuildTarget.StandaloneWindows64)
		{
			return RuntimePlatform.WindowsPlayer.getPlatform(8);
		}
		else if(target == BuildTarget.StandaloneWindows)
		{
			return RuntimePlatform.WindowsPlayer.getPlatform(4);
		}
		else if(target == BuildTarget.Android)
		{
			return RuntimePlatform.Android.getPlatform();
		}
		else if(target == EditorCommonTool.build_target_ios)
		{
			return RuntimePlatform.IPhonePlayer.getPlatform();
		}
		else
		{
			if(Application.isEditor)
			{
				// return Platform.android;
			}
			return Platform.unknown;
		}
	}

	// public static string getSheetDirName()
	// {
	// 	return getSheetDirName(EditorUserBuildSettings.activeBuildTarget);
	// }

	// public static string getSheetDirName(BuildTarget target)
	// {
	// 	return getSheetDirName(getPlatform(target));
	// }

	// public static string getSheetAnimDirName()
	// {
	// 	return getSheetAnimDirName(EditorUserBuildSettings.activeBuildTarget);
	// }


	// public static string getResPath(string path)
	// {
    //     if(path.StartsWith(ConfigTool.bundleDir[0]))
	// 	{
    //         return ConfigTool.bundleDir[0];
	// 	}

	// 	return null;
	// }


	public static void ProcessSelectScene(System.Action<string> callback, bool open = true)
	{
		string oldScenePath = EditorSceneManager.GetActiveScene().path;

		EditorCommonTool.ProcessSelectionObjs("*.unity", (path) =>
			{
                if(!path.EndsWith(".unity"))
                {
                    return;
                }

				if(open)
				{
					if(EditorSceneManager.GetActiveScene().path != path)
					{
						EditorSceneManager.OpenScene(path);
					}
				}

				callback(path);
			});

		if (!string.IsNullOrEmpty(oldScenePath) && EditorSceneManager.GetActiveScene().path != oldScenePath)
		{
			EditorSceneManager.OpenScene(oldScenePath);
		}
	}

    public static void ProcessAllScene(System.Action<string> callBack, bool open = true)
    {
        string oldScenePath = EditorSceneManager.GetActiveScene().path;

        for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
        {
            EditorBuildSettingsScene scene = EditorBuildSettings.scenes[i];
            if (!scene.enabled)
            {
                continue;
            }

            if(open)
            {
                if(EditorSceneManager.GetActiveScene().path != scene.path)
                {
                    EditorSceneManager.OpenScene(scene.path);
                }
            }

            callBack(scene.path);
        }

        if (!string.IsNullOrEmpty(oldScenePath) && EditorSceneManager.GetActiveScene().path != oldScenePath)
        {
            EditorSceneManager.OpenScene(oldScenePath);
        }
    }

    public static void OpenScene(string path)
    {
        if (string.IsNullOrEmpty(path))
        {
            EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);
        }
        else
        {
            EditorSceneManager.OpenScene(path);
        }
    }

    public static void ProcessSelectionObjs(string searchPattern, System.Action<string> callBack)
    {
        Object selectedObj = Selection.activeObject;
        //        if (selectedObj != null)
        //        {
        //            string assetPath = AssetDatabase.GetAssetPath(selectedObj);
        //            callBack(assetPath);
        //        }
        //        else
        {
			for(int j = 0; j < Selection.assetGUIDs.Length; j++)
			{
				string dirPath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[j]);
	            if (System.IO.Directory.Exists(dirPath))
	            {
	                string[] paths = System.IO.Directory.GetFiles(dirPath, searchPattern, System.IO.SearchOption.AllDirectories);
	                for (int i = 0; i < paths.Length; i++)
	                {
	                    callBack(paths[i]);
	                }
	            }
	            else
	            {
	                callBack(dirPath);
	            }
			}
        }
    }
	public static HashSet<string> ParseDiffFile(string filePath)
	{
		HashSet<string> modifiedFiles = new HashSet<string>();
		string str = CommonUtil.fileToString(filePath);
		if (!string.IsNullOrEmpty(str))
		{
			StringReader reader = new StringReader(str);
			while (true)
			{
				string line = reader.ReadLine();
				if (string.IsNullOrEmpty(line))
				{
					break;
				}


				line = line.Replace(".meta", "");
				modifiedFiles.Add(line);
			}
		}
		return modifiedFiles;
	}

//    public static HashSet<string> GetDirAssetPaths(string[] dirs)
//    {
//        HashSet<string> result = new HashSet<string>();
//        string[] assetGuids = AssetDatabase.FindAssets("", dirs);
//        HashSet<string> assetGuidSet = new HashSet<string>(assetGuids);
//        foreach (string assetGuid in assetGuidSet)
//        {
//            string assetPath = AssetDatabase.GUIDToAssetPath(assetGuid);
//            if (File.Exists(assetPath))
//            {
//                result.Add(assetPath);
//            }
//        }
//        return result;
//    }

    public static HashSet<string> FindAssets(string dir, string filter = "")
    {
        return FindAssets(new string[]{dir}, filter);
    }

    public static HashSet<string> FindAssets(string[] dirs, string filter = "")
    {
        HashSet<string> assetPathSet = new HashSet<string>();

        string[] assetGuids = AssetDatabase.FindAssets(filter, dirs);
        HashSet<string> assetGuidSet = new HashSet<string>(assetGuids);
        foreach (string assetGuid in assetGuidSet)
        {
            string assetPath = AssetDatabase.GUIDToAssetPath(assetGuid);
            if (File.Exists(assetPath))
            {
                assetPathSet.Add(assetPath);
            }
        }

        return assetPathSet;
    }
}

